//
// Created by weslywang on 2020/5/6.
//

#include "../common/common.h"

void printVeator(vector<int> &prices) {
    cout << "当前价格队列：大小=" << prices.size() << "，";
    for (int i = 0; i < prices.size(); i++) {
        cout << prices[i] << ",";
    }
    cout << endl;
}

// stage=1 已花费buyPrice购买， stage=0 还未购买，earn 已产生的收益
int profit(vector<int> &prices, int count, int stage, int buyPrice, int earn) {
//    printVeator(prices);
    if (count < 1 || prices.size() < 1) {
        return earn;
    }
    int money1 = 0, money2 = 0;
    vector<int> prices1;
    for (int i = 1; i < prices.size(); i++) {
        prices1.push_back(prices[i]);
    }
//    int tt = prices[0];
//    prices.erase(prices.begin());
//    prices1=prices;
    if (stage == 0) {
        // 尝试买入
        buyPrice = prices[0];
//        cout << "尝试买入=" << buyPrice << "，已产生收益=" << earn << endl;
        money1 = profit(prices1, count, 1, buyPrice, earn);
//        cout << "尝试买入=" << buyPrice << ", 收益=" << money1 << "，已产生收益=" << earn << endl;
        // 放弃当前价格
//        cout << "放弃买入价格=" << buyPrice << "，已产生收益=" << earn << endl;
        money2 = profit(prices1, count, 0, 0, earn);
//        cout << "放弃买入价格=" << buyPrice << ", 收益=" << money2 << "，已产生收益=" << earn << endl;
    } else if (stage == 1) {
        int out = prices[0];
        int income = out - buyPrice;
        if (income > 0) {
            // 尝试卖出
//            cout << "完整交易一次：买入价 " << buyPrice << "，卖出价 " << out << "，当前收益 " << income << "，已产生收益=" << earn << endl;
            money2 = profit(prices1, count - 1, 0, 0, income + earn);
//            cout << "完整交易一次：买入价 " << buyPrice << "，卖出价 " << out << "，当前收益 " << income << "，后续收益 " << money2 << "，已产生收益="<< earn << endl;
        }
        // 放弃当前价格
//        cout << "放弃卖出价格=" << out << "，已产生收益=" << earn << endl;
        money1 = profit(prices1, count, 1, buyPrice, earn);
//        cout << "放弃卖出价格=" << out << ", 收益=" << money1 << "，已产生收益=" << earn << endl;
    }
//    prices.insert(prices.begin(), tt);
    return max(money1, money2);
}

// 运行超时
int maxProfit(vector<int> &prices) {
    int res = 0;
    res = profit(prices, 2, 0, 0, 0);
    return res;
}

// accept 版本
int maxProfit2(vector<int> &prices) {
    int buy1 = INT_MAX, sell1 = 0, buy2 = INT_MAX, sell2 = 0;

    for (int i = 0; i < prices.size(); i++) {
        buy1 = min(buy1, prices[i]);
        sell1 = max(sell1, prices[i] - buy1);
        buy2 = min(buy2, prices[i] - sell1);
        sell2 = max(sell2, prices[i] - buy2);
    }

    return sell2;
}

int main() {
    Common common;
    vector<vector<int>> data = common.loadData();
    for (int i = 0; i <= data.size(); i++) {
        int tmp = maxProfit(data[i]);
        cout << "总收益" << tmp << endl;
        cout << "**************" << endl;
    }
    return 0;
}